package com.whiteape.book.core.engine.helper;

import android.util.Log;

import com.whiteape.book.net.RetrofitHelper;
import com.whiteape.book.utils.FileUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.URLUtils;

import org.json.JSONObject;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

public class JavaBridge {

    private Context rhino;
    private Scriptable scope;
    private int lineNo;

    public JavaBridge(Context rhino, Scriptable scope, int linNo) {
        this.rhino = rhino;
        this.scope = scope;
        this.lineNo = linNo;

    }

    public void loadUrl(String url) {
        Log.e("TWTW", "LLLLLLLLLLLLLLoad url" + url);

        String content = FileUtils.getCachedJsContent(url);
//        System.out.println("HHH content is " + content);
        if (StringUtils.isEmpty(content)) {
            content = getUrl(url);
//            System.out.println("YYY content now is " + content);
        }
        FileUtils.cacheJsRemoteFile(url, content);
        rhino.evaluateString(scope, content, "lib" + lineNo, lineNo, null);
        lineNo++;
    }

    public String getUrl(String url) {
        return getUrl(url, null);
    }

    /**
     *
     * @param url
     * @param headerMap js传过来的json格式的string
     * @return
     */
    public String getUrl(String url, String headerMap) {
        List<Cookie> cookies = RetrofitHelper.getInstance().getCookieJar().loadForRequest(HttpUrl.get(url));
//        for(Cookie cookie : cookies) {
//            System.out.println("cookie is " + cookie.name() + "=>" + cookie.value());
//        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Referer",url);
        try {
            if (!StringUtils.isEmpty(headerMap)) {
                //js传过来的必须是json格式的string
                JSONObject jsonObject = new JSONObject(headerMap);

                Iterator keys = jsonObject.keys();
                while(keys.hasNext()){

                    String key = (String)keys.next();
                    headers.put(key,jsonObject.getString(key));
                }
            }
            return RetrofitHelper.getInstance().getHttpApiImpl(URLUtils.getBaseUrl(url))
                    .downloadByGetWithHeaders(url, headers).execute().body().string();

        } catch (Exception e) {
            return "";
        }
    }

    public String postUrl(String url, String body){
        return postUrl(url, body, null);
    }

    public String postUrl(String url, String body, String headerStr) {
//        List<Cookie> cookies = RetrofitHelper.getInstance().getCookieJar().loadForRequest(HttpUrl.get(url));
//        for(Cookie cookie : cookies) {
//            System.out.println("cookie is " + cookie.name() + "=>" + cookie.value());
//        }
        Map<String, String> headers = new HashMap<>();
        Map<String, String> bodyMap = new HashMap<>();
        headers.put("Referer",url);
        try {
            if (!StringUtils.isEmpty(headerStr)) {

                try{
                    JSONObject jsonObject = new JSONObject(headerStr);

                    Iterator keys = jsonObject.keys();
                    while(keys.hasNext()){

                        String key = (String)keys.next();
                        headers.put(key,jsonObject.getString(key));
                    }
                }catch (Exception e){
                    //如果不是json格式的，那么就是老式的 xxx:bbb;ccc:ddd这种
                    //这种因为分隔ua的时候会出现问题，已经弃用

                    //headerStr内容    Referer:xxxxxxx;Accept:xxxx;Sign:sfdf
                    String[] headerArr = headerStr.split(";");
                    for (String header : headerArr) {
                        String[] headerPart = header.split(":");
                        headers.put(headerPart[0], headerPart[1]);
                    }
                }

            }
            if (!StringUtils.isEmpty(body)) {
                String[] bodyArr = body.split("&");
                for (String bodyStr : bodyArr) {
                    String[] bodyPart= bodyStr.split("=");
                    bodyMap.put(bodyPart[0], bodyPart[1]);
                }
            }
            String ret = RetrofitHelper.getInstance().getHttpApiImpl(URLUtils.getBaseUrl(url))
                    .downloadByPostWithHeaders(url, bodyMap, headers).execute().body().string();
            return ret;

        } catch (Exception e) {
            return "";
        }
    }
}
